//引入axios，进行二次封装
import axios from 'axios'
//引入Element·UI消息对话框和消息的组件
import {
  MessageBox,
  Message
} from 'element-ui'
//引入vuex的store
import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance创建axios实例对象
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url请求根路径的设置
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout 请求的超时时间
})

// request interceptor 请求拦截器
service.interceptors.request.use(
  config => {
    //获取token判断token是否存在
    const token = store.getters.token;
    if (token) {
      //把token嵌入到请求头中进行携带
      // 这里没改代码
      // 把这行代码写5遍 发送qq群里  ok不?
      config.headers['token'] = token;
    }
    return config
  },
  error => {
    //请求的时候出现错误信息，用来调试的
    console.log(error) // 项目上线了在删除/或者
    return Promise.reject(error)
  }
)

// response interceptor响应拦截器
service.interceptors.response.use(

  response => {
    //返回处理后的响应数据
    const res = response.data
    //错误码的信息处理=======================坑
    
    //新添加了 && res.code !==200 代码
    if (res.code !== 20000 && res.code !== 200) {
        alert(res.data)
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    //
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
